

{% extends "layout.html" %}
{% block content %}
<div class="container mt-5">
    <h1 class="text-center mb-4">欢迎, {{ current_user.username }}</h1>
    <p class="text-center lead">探索即时问答和互动聊天功能。</p>
    <div id="chatHistory" class="text-center mb-5">
        {% for message in messages[:-1] %}  <!-- 排除最后一条消息 -->
            <div class="{{ 'text-primary' if message.role == 'user' else 'text-info' }}">
                <strong>{{ "我:" if message.role == 'user' else "机器人:" }}</strong> {{ message.content }}
            </div>
        {% endfor %}
    </div>
    <!-- 动态显示文本的容器，添加样式 -->
    <div id="dynamicResponseText" class="text-center mb-4"></div>
    <form id="chataskForm" action="{{ url_for('public.chatask') }}" method="post" class="text-center">
        {{ form.hidden_tag() }}
        <div class="form-group">
            {{ form.chataskbox(class="form-control-lg w-75 mx-auto", placeholder="输入您的对话...", id="chataskbox") }}
        </div>
        <div>
            {{ form.submit(class="btn btn-primary btn-lg") }}
            <button type="button" id="stopButton" class="btn btn-danger btn-lg ml-2">停止</button> <!-- 增加了停止按钮 -->
        </div>
    </form>
</div>
<script>
    let shouldStop = false; // 控制是否停止输出的标志变量
    let responseText = `{{ response_text|safe }}`;
    let container = document.getElementById('dynamicResponseText');
    let index = 0;

    function showText() {
        if (index < responseText.length && !shouldStop) {
            container.innerHTML += responseText.charAt(index);
            index++;
            setTimeout(showText, 100);
        } else {
            // 文本显示完毕后清空输入框
            document.getElementById('chataskbox').value = ''; // 清空输入框
        }
    }

    // 添加停止按钮的事件监听器
    document.getElementById('stopButton').addEventListener('click', () => {
        shouldStop = true; // 用户点击停止按钮时设置标志变量为true
    });

    // 只有当responseText不为None时才执行
    if (responseText && responseText != 'None') {
        showText(); // 如果有文本则开始显示
    }
</script>
{% endblock %}
